const Service = require('egg').Service;

class WxmsgdbService extends Service {
  // 保存私聊消息
  async create(data) {
    const { ctx } = this;
    delete data.data.finalFromWxid;
    delete data.data.atWxidList;
    delete data.data.silence;
    delete data.data.finalfrom_groupnick;
    delete data.data.membercount;
    data.date = new Date(Number(data.timestamp) + 8 * 60 * 60 * 1000);
    try {
      const result = await ctx.model.Wxmsgdb.create(data);
      // 更新好友的 updatedAt
      await ctx.model.Wxfriend.findOneAndUpdate({ownerWxid:data.wxid,wxid: data.data.fromWxid}, { updatedAt: result.date });      
      return result;
    } catch (err) {
      this.ctx.logger.error('保存私聊消息失败:', err);
      return null;
    }
  }

  // 根据条件查询群聊消息
  async find(query = {}, options = {}) {
    const { ctx } = this;
    try {
      const result = await ctx.model.Wxmsgdb.find(query, null, options);
      return result;
    } catch (err) {
      this.ctx.logger.error('查询群聊消息失败:', err);
      return [];
    }
  }

  // 根据ID查找单条群聊消息
  async findById(id) {
    const { ctx } = this;
    try {
      const result = await ctx.model.Wxmsgdb.findById(id);
      return result;
    } catch (err) {
      this.ctx.logger.error('根据ID查询群聊消息失败:', err);
      return null;
    }
  }

  // 根据ID删除群聊消息
  async deleteById(id) {
    const { ctx } = this;
    try {
      const result = await ctx.model.Wxmsgdb.findByIdAndDelete(id);
      return result;
    } catch (err) {
      this.ctx.logger.error('删除私聊消息消息失败:', err);
      return null;
    }
  }
}

module.exports = WxmsgdbService;
